<?php
/**
 * 配方V1.0
 * 配方页面
 * @author qi
 * @date 2018/05/18
 *
 */

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\LogService;
use service\ToolsService;
use think\Db;


class Formula extends BasicAdmin
{

    public $table = 'Formula';
    public $SystemAttribute = 'SystemAttribute';
    public $ProductAttribute = 'SystemCategory';
    /**
     * 当前页面标题
     * @var string
     */
    public $title = '配方管理';

    /**
     *  分类列表
     */
    public function index()
    {
        $db = Db::name($this->table);
        $title = $this->request->get("title");
        $db->whereLike('name',"%".$title."%");
        return parent::_list($db);
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_data_filter(&$data)
    {
        $cate = Db::name('system_attribute')->where(array('pid' => 0))->order("sort asc")->select();
        foreach ($data as $key => &$item) {
            foreach ($cate as $key2 => &$item2) {
                $nameArr = Db::name("formula_attr")->where(['cid' => $item2['id'], 'pid' => $item['id']])->column("attrname");
                $name = implode(",", $nameArr);
                $item['value'][$key2] = $name;
            }
        }
        $this->assign('category', $cate);



    }

    /**
     * @param $cid 配方属性问题
     * @param $pid 配方id
     * @param int $isArray 返回类型
     * @return string
     */
    public function getAttrname($cid, $pid, $isArray = 0)
    {
        $nameArr = Db::name("system_attribute")->alias('s')->join("formula_attr f", 's.id = f.attr', 'LEFT')->where(["f.cid" => $cid, "f.pid" => $pid])->select();
        if ($nameArr) {
            if ($isArray) {
                return $nameArr;
            } else {
                return implode(array_column($nameArr, "abbr"), ",");
            }
        } else {
            return array();
        }

    }

    /**
     * 表单数据默认处理
     * @param array $data
     */
    public function _form_filter(&$data)
    {
        Header("Content-type: application/pdf");// 文件将被称为 downloaded.pdf
        header("Content-Disposition:inline;filename='downloaded.pdf'");
        if ($this->request->isPost()) {
            $attr = $data['attr'] = array();
            $attrnameArr = $_POST['attrname'];
            $typeArr = $_POST['type'];
            $attridArr = $_POST['attrid'];

            $data['create_time'] = time();
            $data['create_by'] = session('user.id');

            foreach ($attrnameArr as $k => $r) {
                $attr[$k]['cid'] = $typeArr[$k];
                $attr[$k]['attr'] = $attridArr[$k];;
                $attr[$k]['attrname'] = $attrnameArr[$k];
            }
            $data['attr'] = $attr;
        } else {
            if (isset($data['id'])) {
                $pid = $data['id'];
                if (isset($_GET['id'])) {
                    $attr = Db::name('formula_attr')->where(array('pid' => $pid))->select();
                    $title = $data['name'];
                    $this->assign('title', $title);
                    $this->assign('attr', $attr);
                }
            } else {
                $pid = 0;
            }
            $cate = Db::name('system_attribute')->where(array('pid' => 0,'pids'=>1))->order("sort asc")->select();
            $cate2 = Db::name('system_attribute')->where(array('pid' => 0,"pids"=>2))->order("sort asc")->select();
            $this->assign('category', $cate);
            $this->assign('category2', $cate2);

        }
    }

    /**
     * 添加-分类
     */
    public function add()
    {
        return $this->_form($this->table, 'form');
    }

    //配方添加属性
    public function attr()
    {
        return $this->_attr($this->table, 'attr');
    }

    public function _attr_filter(&$data)
    {
        if (isset($_GET['type'])) {
            $type = $_GET['type'];
            //第一级分类
            $ptype = $_GET['ptype'];
            $pids = Db::name("system_attribute")->where("id",$ptype)->value("pids");
            //分类主要id
            $pid = $_GET['pid'];
            $data['pid'] = $pid;
            $attr = self::getAllAttr2($type);
            $cattr = self::getAttr($type, $pid);
            if (!empty($cattr)) {
                $data['attr'] = array_column($cattr, 'attr');

            } else {
                $data['attr'] = array();
            }
            $data['type'] = $type;
            $this->assign("attr", $attr);
            $this->assign("ptype", $ptype);
            $this->assign("pids", $pids);
        }

    }

    /**
     * 编辑-分类
     */
    public function edit()
    {
        return $this->_form($this->table, 'form');
    }

    /**
     * 删除-分类
     */
    public function del()
    {
        if (DataService::update($this->table)) {
            LogService::write('配方删除', '配方删除');
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }

    public function getAttr($cid, $pid = 0)
    {
        $categorys = Db::name("formula_attr")->where("pid", $pid)->where("cid", $cid)->order('id desc')->select();
        foreach ($categorys as $key => &$item) {
            $count = Db::name($this->SystemAttribute)->where("pid", $item['id'])->count();
            if ($count) {
                $item['count'] = $count;
            } else {
                $item['count'] = 0;
            }


        }
        return $categorys;
    }

    public function getAllAttr($pid = 0)
    {

        $categorys = self::GetTeamMember($pid);
        return $categorys;
    }

    public function getAllAttr2($pid)
    {
        $categorys = Db::name($this->SystemAttribute)->where("pid", $pid)->order('id asc')->select();
        foreach ($categorys as $key => &$item) {
            $count = Db::name($this->SystemAttribute)->where("pid", $item['id'])->count();
            if ($count) {
                $item['count'] = $count;
            } else {
                $item['count'] = 0;
            }
        }
        return $categorys;
    }

    public function ajaxgetAttr()
    {
        //配方id
        if (!empty($_GET['pid'])) {
            $pid = $_GET['pid'];
        }else{
            $pid = 0;
        }
        //分配父级id
        if (!empty($_GET['cid'])) {
            $cid = $_GET['cid'];
        } else {
            $cid = 0;
        }
        //配方所有属性
        $fattr = $categorys = Db::name("formula_attr")->where("pid", $pid)->select();
        //父级分类所有属性
        $categorys = Db::name($this->SystemAttribute)->where("pid", $cid)->order('id desc')->select();

        foreach ($categorys as $key => &$item) {
            //判断有没有下级分类
            $count = Db::name($this->SystemAttribute)->where("pid", $item['id'])->count();
            if ($count) {
                $item['count'] = $count;
            } else {
                $item['count'] = 0;
            }
            //配方属性的最上级id
            if (!empty($_GET['ptype'])) {
                $item['ptype'] = $ptype = $_GET['ptype'];
            }
            $item['checked'] = "";
            $item['desc'] = "";
            $item['pieces'] = "";
            $item['order'] = "";
            foreach ($fattr as $key => &$item2) {
                if ($item2['attr'] == $item['id']) {
                    $item['checked'] = "checked";
                    $item['desc'] = $item2['desc'];
                    $item['pieces'] = $item2['pieces'];
                    $item['order'] = $item2['order'];
                }
            }
        }
        return json($categorys);
    }

    function GetTeamMember($pid)
    {
        $categorys = Db::name($this->SystemAttribute)->order('id desc')->select();
        $Teams = array();//最终结果
        $mids = array($pid);//第一次执行时候的用户id
        do {
            $othermids = array();
            $state = false;
            foreach ($mids as $valueone) {
                foreach ($categorys as $key => $valuetwo) {
                    if ($valuetwo['pid'] == $valueone) {
                        $Teams[] = $valuetwo;
                        $othermids[] = $valuetwo['id'];
                        array_splice($categorys, $key, 1);
                        $state = true;
                    }
                }
            }
            $mids = $othermids;
        } while ($state == true);
        $Teams = ToolsService::arr2table($Teams);
        return $Teams;
    }


}

